package com.xgkj.diyiketang.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.easemob.easeui.domain.EaseUser;
import com.xgkj.diyiketang.activity.data.GradeAdapter;
import com.xgkj.diyiketang.activity.data.SubjectAdapter;
import com.xgkj.diyiketang.data.CityInfo;
import com.xgkj.diyiketang.data.CountryInfo;
import com.xgkj.diyiketang.data.SchoolInfo;
import com.xgkj.diyiketang.hxsdk.DemoHelper;
import com.xgkj.diyiketang.hxsdk.PreferenceManager;
import com.xgkj.diyiketang.task.AreaCitySchoolTask;
import com.xgkj.diyiketang.task.UpdateUserInfoTask;
import com.xgkj.diyiketang.util.PopupHelper;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.UpdateIconTask;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.GetImagePathUtil;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.weidget.ClearableEditText;
import com.xgkj.diyiketang.weidget.RoundImageView;
import com.xgkj.diyiketang.weidget.kankan.OnWheelChangedListener;
import com.xgkj.diyiketang.weidget.kankan.OnWheelClickedListener;
import com.xgkj.diyiketang.weidget.kankan.WheelView;
import com.xgkj.diyiketang.weidget.kankan.adapters.ArrayWheelAdapter;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserInfoActivity extends BaseActivity implements View.OnClickListener, OnWheelChangedListener, OnWheelClickedListener {
    private Context mContext;
    private RelativeLayout headImgLayout;
    private RelativeLayout nickNameLayout;
    private RelativeLayout personSigatureLayout;
    private RoundImageView mHeadImageView;
    private ClearableEditText nickNameText;
    private ClearableEditText personSigatureText;
    //    private ClearableEditText userSex;
    private PopupWindow popWindow;
    private static final int CAMERA_REQUEST = 0;
    private static final int CHOOSE_REQUEST = 11;
    private static final int CROP_REQUEST = 2;
    private File mFile;
    private String local_url;
    private static final String CAMERA_FILE = "diyiketang/img";
    private int taskId = -1;
    private EatShowUserInfo userInfo;
    private String old_url;
    private PopupWindow mPopWindow;
    private TextView sexView;
    private TextView saveText;
    private int saveTaskId = -1;
    private int ishaveJLPTaskId = -1;
    private int getSchoolTaskId = -1;
    private String[] allCounties;
    protected Map<String, String[]> mSchoolDatasMap = new HashMap<String, String[]>();
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    /**
     * 当前省的名称
     */
    protected String mCurrentProviceName;
    /**
     * 当前学校的名称
     */
    protected String mCurrentDistrictName = "";
    /**
     * 当前市的名称
     */
    protected String mCurrentCityName;
    private String mNick;
    private String mSign;
    //    private boolean sexB;
//    private String mSexString;
    InputMethodManager im;

    private String mSchool;
    private ClearableEditText schoolEdit;
    private String mGrade;
    private TextView gradeEdit;
    private PopupHelper mGradePopWindow;
    private GradeAdapter mGradeAdapter;
    private String mSex;
    private int screenWidth;
    private PopupHelper mSubjectPopWindow;
    private TextView kemu;
    private SubjectAdapter mSubjectAdapter;
    private String mSubjectNo;
    private RelativeLayout kemuLayout;
    private String subject;
    private TextView area;
    private String mArea;
    private LinearLayout address_pop;
    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;
    private Button mBtnConfirm;
    private Button mBtnCancel;
    private boolean isVisiable = false;
    private RelativeLayout areaLayout;
    private RelativeLayout edu;
    private String youeryuan;
    private String xiaoxue;
    private String chuzhong;
    private String gaozhong;
    private String daxue;
    private String shuoshi;
    private String boshi;
    private String work;
    private TextView classEdit;
    private String mClass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.userinfo);
        mContext = this;
        File folder = EatShowSetting.getInstance(mContext).getDataFolder(CAMERA_FILE);
        String fileName = "IMG" + System.currentTimeMillis() + ".jpeg";
        mFile = new File(folder, fileName);
        screenWidth = ViewUtil.getScreenWidth(mContext);
        initView();
        im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        doGetAreaSchool();
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateUserInfo();
    }

    private void updateUserInfo() {
        userInfo = getEatShowApp().getmUserInfo();
        String replace = mArea.replace(";", " ");
        area.setText(replace);
        if (userInfo != null) {
            subject = userInfo.getSubjectNo();
            String head_url = userInfo.getUserLogo();
            if (head_url != null && head_url.length() > 0 && !head_url.equals(old_url)) {
                ImageCache.getInstance(mContext).loadBitmapToView(mHeadImageView, head_url, new ViewUtil.Size(ViewUtil.dip2px(mContext, 70), ViewUtil.dip2px(mContext, 70)));
                old_url = head_url;
            }
            try {
                nickNameText.setText(URLDecoder.decode(userInfo.getNickName(), "utf-8"));
                if (!TextUtils.isEmpty(userInfo.getCla())) {
                    classEdit.setText(URLDecoder.decode(userInfo.getCla(), "utf-8"));
                } else {
                    classEdit.setText("1");
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (!TextUtils.isEmpty(userInfo.getUserSign())) {
                try {
                    personSigatureText.setText(URLDecoder.decode(userInfo.getUserSign(), "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            if (!TextUtils.isEmpty(userInfo.getSex())) {
                if (userInfo.getSex().equals("true")) {
                    mSex = "true";
                    sexView.setText("男");
                } else {
                    mSex = "false";
                    sexView.setText("女");
                }
            }


            mSchool = getEatShowApp().getmUserInfo().getSchoolName();
            schoolEdit.setText(mSchool);
            if (!TextUtils.isEmpty(mSchool)) {
//                schoolEdit.setFocusable(false);
                schoolEdit.setEnabled(false);
            }
            mGrade = getEatShowApp().getmUserInfo().getBelongGrade();
            if (mGrade != null && mGrade.equals("1")) {
                gradeEdit.setText("一年级");
            } else if (mGrade != null && mGrade.equals("2")) {
                gradeEdit.setText("二年级");
            } else if (mGrade != null && mGrade.equals("3")) {
                gradeEdit.setText("三年级");
            } else if (mGrade != null && mGrade.equals("4")) {
                gradeEdit.setText("四年级");
            } else if (mGrade != null && mGrade.equals("5")) {
                gradeEdit.setText("五年级");
            } else if (mGrade != null && mGrade.equals("6")) {
                gradeEdit.setText("六年级");
            } else if (mGrade != null && mGrade.equals("7")) {
                gradeEdit.setText("初一");
            } else if (mGrade != null && mGrade.equals("8")) {
                gradeEdit.setText("初二");
            } else if (mGrade != null && mGrade.equals("9")) {
                gradeEdit.setText("初三");
            } else if (mGrade != null && mGrade.equals("10")) {
                gradeEdit.setText("高一");
            } else if (mGrade != null && mGrade.equals("11")) {
                gradeEdit.setText("高二");
            } else if (mGrade != null && mGrade.equals("12")) {
                gradeEdit.setText("高三");
            } else if (mGrade != null && mGrade.equals("13")) {
                gradeEdit.setText("早教");
            } else if (mGrade != null && mGrade.equals("14")) {
                gradeEdit.setText("幼儿园");
            } else if (mGrade != null && mGrade.equals("15")) {
                gradeEdit.setText("综合");
            }


            if (userInfo.getUserType() == 1) {
                kemuLayout.setVisibility(View.VISIBLE);
                if (subject != null && subject.equals("0")) {
                    mSubjectNo = "0";
                    kemu.setText("语文");
                } else if (subject != null && subject.equals("1")) {
                    mSubjectNo = "1";
                    kemu.setText("数学");
                } else if (subject != null && subject.equals("2")) {
                    mSubjectNo = "2";
                    kemu.setText("外语");
                } else if (subject != null && subject.equals("3")) {
                    mSubjectNo = "3";
                    kemu.setText("综合");
                }
            } else {
                kemuLayout.setVisibility(View.GONE);
            }

//            if (userInfo.getSex().equals("男")){
//                sexB = true;
//            }else{
//                sexB = false;
//            }
        }
    }


    private void initView() {
        Bundle bundle = getIntent().getBundleExtra("school");
        youeryuan = bundle.getString("youeryuan");
        xiaoxue = bundle.getString("xiaoxue");
        chuzhong = bundle.getString("chuzhong");
        gaozhong = bundle.getString("gaozhong");
        daxue = bundle.getString("daxue");
        shuoshi = bundle.getString("shuoshi");
        boshi = bundle.getString("boshi");
        work = bundle.getString("work");
        mArea = bundle.getString("area");
        ((TextView) findViewById(R.id.back)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        headImgLayout = (RelativeLayout) findViewById(R.id.head_img_layout);
        mHeadImageView = (RoundImageView) findViewById(R.id.head_img);
        nickNameLayout = (RelativeLayout) findViewById(R.id.nickname_layout);
        nickNameText = (ClearableEditText) findViewById(R.id.nickname);
        personSigatureLayout = (RelativeLayout) findViewById(R.id.person_signature_layout);
        personSigatureText = (ClearableEditText) findViewById(R.id.person_signature);
        //userSex = (ClearableEditText) findViewById(R.id.user_sex);
        headImgLayout.setOnClickListener(this);
        sexView = (TextView) findViewById(R.id.user_sex);
        sexView.setOnClickListener(this);
        area = (TextView) findViewById(R.id.area);
        area.setOnClickListener(this);
        area.setClickable(false);
//        nickNameLayout.setOnClickListener(this);
//        personSigatureLayout.setOnClickListener(this);
        saveText = (TextView) findViewById(R.id.saveinfo);
        saveText.setOnClickListener(this);
        schoolEdit = (ClearableEditText) findViewById(R.id.school_edit);

        gradeEdit = (TextView) findViewById(R.id.grade);
        gradeEdit.setOnClickListener(this);

        classEdit = (TextView) findViewById(R.id.class_txt);
        classEdit.setOnClickListener(this);

        kemuLayout = (RelativeLayout) findViewById(R.id.kemu_Layout);
        kemu = (TextView) findViewById(R.id.grade_kemu);
        kemu.setOnClickListener(this);

        address_pop = (LinearLayout) findViewById(R.id.address_pop);
        address_pop.setVisibility(View.GONE);
        mViewProvince = (WheelView) findViewById(R.id.id_province);

        areaLayout = (RelativeLayout) findViewById(R.id.area_Layout);
        areaLayout.setOnClickListener(this);

        edu = ((RelativeLayout) findViewById(R.id.edu_layout));
        edu.setOnClickListener(this);
        setUpViews();
        initPopWindow();
        setUpListener();
        initSexPopWindow();
        updateUserInfo();
    }

    private void setUpViews() {
        mViewProvince = (WheelView) findViewById(R.id.id_province);
        mViewCity = (WheelView) findViewById(R.id.id_city);
        mViewDistrict = (WheelView) findViewById(R.id.id_district);
        mBtnConfirm = (Button) findViewById(R.id.btn_confirm);
        mBtnCancel = (Button) findViewById(R.id.btn_cancel);
    }

    private void setUpListener() {
        // 添加change事件
        mViewProvince.addChangingListener(this);
        // 添加change事件
        mViewCity.addChangingListener(this);
        // 添加change事件
        mViewDistrict.addChangingListener(this);
//        mViewDistrict.addClickingListener(this);
        // 添加onclick事件
        mBtnConfirm.setOnClickListener(this);
        mBtnCancel.setOnClickListener(this);
    }

    private void initSexPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.choose_sex, null);
        view.findViewById(R.id.nan).setOnClickListener(this);
        view.findViewById(R.id.nv).setOnClickListener(this);
        mPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopWindow.setBackgroundDrawable(new ColorDrawable());
        mPopWindow.setFocusable(true);
        mPopWindow.setOutsideTouchable(true);
    }

    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.popwindow,
                null);
        ((Button) view.findViewById(R.id.takephoto)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.choosephoto)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.cancle)).setOnClickListener(this);
        popWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);

        mGradeAdapter = new GradeAdapter(mContext);
        mGradePopWindow = new PopupHelper(mContext, mGradeAdapter);

        mGradePopWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mGradePopWindow.dismissDropDownView();
                mGrade = String.valueOf(position + 1);
                gradeEdit.setText((String) mGradeAdapter.getItem(position));
                mGradeAdapter.setSelectPosition(position);
            }
        });

        mSubjectAdapter = new SubjectAdapter(mContext, 1);
        mSubjectPopWindow = new PopupHelper(mContext, mSubjectAdapter);
        mSubjectPopWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSubjectPopWindow.dismissDropDownView();
                if (position == 0) {
                    mSubjectNo = null;
                    return;
                } else {
                    mSubjectNo = String.valueOf(position - 1);
                }
                kemu.setText((String) mSubjectAdapter.getItem(position));
                mSubjectAdapter.setSelectPosition(position);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_sex:
                im.hideSoftInputFromWindow(UserInfoActivity.this.getCurrentFocus().getWindowToken(), 0);
                mPopWindow.showAtLocation(v, Gravity.BOTTOM, 0, 30);
                break;
            case R.id.nan:
                mSex = "true";
                sexView.setText(R.string.sex_nan);
                mPopWindow.dismiss();
                break;
            case R.id.nv:
                mSex = "false";
                sexView.setText(R.string.sex_nv);
                mPopWindow.dismiss();
                break;
            case R.id.head_img_layout:
                im.hideSoftInputFromWindow(UserInfoActivity.this.getCurrentFocus().getWindowToken(), 0);
                popWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.nickname_layout:
                Intent nickname_intent = new Intent(mContext, UpdateNickNameActivity.class);
                startActivity(nickname_intent);
                break;
            case R.id.person_signature_layout:
                Intent signature_intent = new Intent(mContext, UpdateSigature.class);
                startActivity(signature_intent);
                break;
            case R.id.takephoto:
                popWindow.dismiss();
                Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                camera_intent
                        .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
                startActivityForResult(camera_intent, CAMERA_REQUEST);
                break;
            case R.id.choosephoto:
                popWindow.dismiss();
//                Intent intent = new Intent(mContext, PhoneMainActivity.class);
//                startActivityForResult(intent,300);
                Intent choose_intent = new Intent();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    choose_intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                } else {
                    choose_intent.setAction(Intent.ACTION_GET_CONTENT);
                }
                choose_intent.setType("image/*");
                startActivityForResult(choose_intent, CHOOSE_REQUEST);
                break;
            case R.id.cancle:
                popWindow.dismiss();
                break;
            case R.id.saveinfo:

                if (checkInput()) {
                    doUpdate();
                }
                break;

            case R.id.grade:
                try {
                    im.hideSoftInputFromWindow(UserInfoActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mGradePopWindow.showAtLocationView(v, Gravity.BOTTOM, 0, 0);
                break;

            case R.id.grade_kemu:
                try {
                    im.hideSoftInputFromWindow(UserInfoActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mSubjectPopWindow.showAtLocationView(v, Gravity.BOTTOM, 0, 30);
                break;
            case R.id.area:
                if (isVisiable == false) {
                    isVisiable = true;
                    address_pop.setVisibility(View.VISIBLE);
                } else {
                    isVisiable = false;
                    address_pop.setVisibility(View.GONE);
                }
                im.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
                break;
            case R.id.area_Layout:
//                Intent cintent = new Intent(mContext, CityListActivity.class);
//                startActivityForResult(cintent, 1);
//                doGetAreaSchool();

                break;

            case R.id.btn_confirm:
                address_pop.setVisibility(View.GONE);
                area.setText(mCurrentProviceName + " " + mCurrentCityName + " " + mCurrentDistrictName);
//                FragmentManager fm = getActivity().getSupportFragmentManager();
//                xxxFragment = (xxxFragment)fm.findFragmentByTag("xxx")
//                Fragment_TuiJian ft = (Fragment_TuiJian) getFragmentManager().findFragmentByTag(FRAGMENT_KEY_TUIJIAN);
//                ft.setSchoolName(mCurrentDistrictName);
//                ft.getViewList();
                break;
            case R.id.btn_cancel:
                address_pop.setVisibility(View.GONE);
                break;

            case R.id.edu_layout:
                Intent intent = new Intent(UserInfoActivity.this, EduExperienceActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("youeryuan", youeryuan);
                bundle.putString("xiaoxue", xiaoxue);
                bundle.putString("chuzhong", chuzhong);
                bundle.putString("gaozhong", gaozhong);
                bundle.putString("daxue", daxue);
                bundle.putString("shuoshi", shuoshi);
                bundle.putString("boshi", boshi);
                bundle.putString("work", work);
                intent.putExtra("school", bundle);
                finish();
                startActivity(intent);
                break;
            default:
                break;
        }
    }


    private boolean checkInput() {
        mNick = nickNameText.getText().toString();
        mSign = personSigatureText.getText().toString();
        mSchool = schoolEdit.getText().toString();
        if (classEdit.getText().toString() != null) {
            mClass = classEdit.getText().toString();
        } else {
            mClass = "1";
        }
//        mSexString = sexView.getText().toString();
//        if (mSexString.equals("男")){
//            sexB = true;
//        }else{
//            sexB = false;
//        }
        if (TextUtils.isEmpty(mNick)) {
            Toast.makeText(mContext, R.string.no_nick, Toast.LENGTH_SHORT).show();
            return false;
        } else if (TextUtils.isEmpty(mSign)) {
            Toast.makeText(mContext, R.string.sigature_not_null, Toast.LENGTH_SHORT).show();
            return false;
        }

        if (ViewUtil.isNull(mSchool) || ViewUtil.isNull(mGrade)) {
            ToastUtil.showMessage(mContext, R.string.message_not_null);
            return false;
        }

        return true;
    }

    private void doUpdate() {
        String mArea = "";
        String real = getEatShowApp().getmUserInfo().getTrueName();
//        if (mCurrentProviceName != null) {
//            mArea = mCurrentProviceName;
//        } else if (mCurrentProviceName != null && mCurrentCityName != null) {
//            mArea = mCurrentProviceName + ";" + mCurrentCityName;
//
//        } else if (mCurrentProviceName != null && mCurrentCityName != null && mCurrentDistrictName != null) {
//        }
        mArea = mCurrentProviceName + ";" + mCurrentCityName + ";" + mCurrentDistrictName;
//        mArea = area.getText()+"";
        UpdateUserInfoTask uTask = new UpdateUserInfoTask(mSchool, mGrade, real, mSex, mNick, mSign, mSubjectNo, mArea, mClass);
        uTask.addListener(uploadImageListener);
        saveTaskId = getEatShowApp().getTaskManager().addTask(uTask);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_REQUEST:
                if (!mFile.exists()) {
                    return;
                }
                Uri uri = Uri.fromFile(mFile);
                startPhotoZoom(uri);
//                uploadImage(mFile.getAbsolutePath());
                break;

            case CHOOSE_REQUEST:
                if (resultCode != RESULT_OK) {
                    return;
                }
                if (data == null)
                    return;
                Uri choose_uri = data.getData();
                startPhotoZoom(choose_uri);
                break;

            case CROP_REQUEST:
                if (resultCode != RESULT_OK) {
                    return;
                }
                if (data == null)
                    return;
                Bitmap bitmap = (Bitmap) data.getExtras().get("data");
                mHeadImageView.setImageBitmap(bitmap);
                BufferedOutputStream out = null;
                try {
                    out = new BufferedOutputStream(new FileOutputStream(mFile));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG,
                        100, out);
                uploadImage(mFile.getAbsolutePath());
                break;

            case 300:
                PalLog.e("返回resultcode", resultCode + "");
                break;

            default:
                break;
        }
    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            local_url = GetImagePathUtil.getPath(mContext, uri);
            uri = Uri.fromFile(new File(local_url));
        }
        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 360);
        intent.putExtra("outputY", 360);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_REQUEST);
    }

    private void uploadImage(String path) {
        if (taskId != -1) {
            return;
        }

        UpdateIconTask task = new UpdateIconTask(path);
        task.addListener(uploadImageListener);
        taskId = getEatShowApp().getTaskManager().addTask(task);
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println("图片路径:"+path);
//                String url = doPost();
//                System.out.println("头像地址:"+url);
//            }
//        }).start();
    }


    private TaskEventListener uploadImageListener = new ShowToastTaskEventListener(this) {
        @Override
        public void handleTaskCompleted(int taskid, int result, Object data) {
            super.handleTaskCompleted(taskid, result, data);
            if (taskid == taskId) {

                taskId = -1;
                if (data != null) {
                    JSONObject json = (JSONObject) data;
                    String logo_url = json.getString("imageURL");
                    getEatShowApp().getmUserInfo().setUserLogo(logo_url);
                    PreferenceManager.getInstance().setCurrentUserAvatar(logo_url);
                    EatShowUserInfo myInfo = getEatShowApp().getmUserInfo();
                    EaseUser user = DemoHelper.getInstance().getUserProfileManager().getCurrentUserInfo();
                    user.setNick(myInfo.getNickName());
                    user.setAvatar(logo_url);
                    DemoHelper.getInstance().saveContact(user);

                }
                if (mFile.exists()) {
                    mFile.delete();
                }
            } else if (taskid == saveTaskId) {
                getEatShowApp().getmUserInfo().setNickName(mNick);
                getEatShowApp().getmUserInfo().setCla(mClass);
                getEatShowApp().getmUserInfo().setSex(String.valueOf(mSex));
                getEatShowApp().getmUserInfo().setUserSign(mSign);
                PreferenceManager.getInstance().setCurrentUserNick(mNick);

                getEatShowApp().getmUserInfo().setSchoolName(mSchool);
                getEatShowApp().getmUserInfo().setBelongGrade(mGrade);
                getEatShowApp().getmUserInfo().setSubjectNo(mSubjectNo);
                ToastUtil.showMessage(mContext, "修改成功");
                EatShowUserInfo myInfo = getEatShowApp().getmUserInfo();
                EaseUser user = DemoHelper.getInstance().getUserProfileManager().getCurrentUserInfo();
                user.setNick(mNick);
                user.setAvatar(myInfo.getUserLogo());
                DemoHelper.getInstance().saveContact(user);
                finish();
            }

        }

        @Override
        public void handleTaskError(int taskid, int errorCode, String errorMsg) {
            super.handleTaskError(taskid, errorCode, errorMsg);
            if (taskid == taskId) {
                taskId = -1;
            } else if (taskid == saveTaskId) {
                saveTaskId = -1;
            }
        }

        @Override
        public void handleTaskMessage(int taskid, Object data) {
            super.handleTaskMessage(taskid, data);
        }
    };

    private String doPost() {
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";

        URL uri = null;
        try {
            uri = new URL("http://10.0.1.46/liveshow/800009");
            HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
            conn.setConnectTimeout(120 * 1000);
            conn.setReadTimeout(120 * 1000); // 缓存的最长时间
            conn.setDoInput(true);// 允许输入
            conn.setDoOutput(true);// 允许输出
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST");
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
                    + ";boundary=" + BOUNDARY);

            // 首先组拼文本类型的参数
            StringBuilder sb = new StringBuilder();
//            for ( Map.Entry < String , String > entry : params.entrySet ( ) )
//            {
//                sb.append ( PREFIX ) ;
//                sb.append ( BOUNDARY ) ;
//                sb.append ( LINEND ) ;
//                sb.append ( "Content-Disposition: form-data; name=\""
//                        + entry.getKey ( ) + "\"" + LINEND ) ;
//                sb.append ( "Content-Type: text/plain; charset="
//                        + CHARSET + LINEND ) ;
//                sb.append ( "Content-Transfer-Encoding: 8bit" + LINEND ) ;
//                sb.append ( LINEND ) ;
//                sb.append ( entry.getValue ( ) ) ;
//                sb.append ( LINEND ) ;
//            }
            conn.connect();
            DataOutputStream outStream = new DataOutputStream(
                    conn.getOutputStream());
            outStream.write(sb.toString().getBytes());
            // 发送文件数据
//            if ( files != null )
//                for ( Map.Entry < String , File > file : files.entrySet ( ) )
//                {
            StringBuilder sb1 = new StringBuilder();
            sb1.append(PREFIX);
            sb1.append(BOUNDARY);
            sb1.append(LINEND);
            sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""
                    + mFile.getName() + "\"" + LINEND);
            sb1.append("Content-Type: application/octet-stream; charset="
                    + CHARSET + LINEND);
            sb1.append(LINEND);
            outStream.write(sb1.toString().getBytes());

            InputStream is = new FileInputStream(mFile);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }

            is.close();
            outStream.write(LINEND.getBytes());
//                }

            // 请求结束标志
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND)
                    .getBytes();
            outStream.write(end_data);
            outStream.flush();
            // 得到响应码
            int res = conn.getResponseCode();
            InputStream in = conn.getInputStream();
            if (res == 200) {
                int ch;
                StringBuilder sb2 = new StringBuilder();
                byte[] readByte = new byte[512];
                while ((ch = in.read(readByte)) != -1) {
//                    sb2.append((char) ch);
                    String s = new String(readByte, 0, ch);
                    sb2.append(s);
                }
                return sb2.toString();
            }
            outStream.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onItemClicked(WheelView wheel, int itemIndex) {
        if (wheel == mViewDistrict) {
//            address_pop.setVisibility(View.GONE);
            mViewDistrict.setCurrentItem(itemIndex, true);
            mCurrentDistrictName = mSchoolDatasMap.get(mCurrentCityName)[itemIndex];
            address_pop.setVisibility(View.GONE);
            area.setText(mCurrentDistrictName);
            ToastUtil.showMessage(mContext, mCurrentDistrictName);
        }
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict) {
            if (mSchoolDatasMap.get(mCurrentCityName) != null && mSchoolDatasMap.get(mCurrentCityName).length > 0) {
                mCurrentDistrictName = mSchoolDatasMap.get(mCurrentCityName)[newValue];
            } else {
                mCurrentDistrictName = "";
            }


//            new Handler().postDelayed(new Runnable(){
//                public void run() {
//                    address_pop.setVisibility(View.GONE);
//                    ToastUtil.showMessage(mContext, mCurrentDistrictName);
//                    local_video.setText(mCurrentDistrictName);
//                }
//            }, 1000);
        }
    }

    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        String[] citys = mCitisDatasMap.get(mCurrentProviceName);
        String[] areas = null;
        if (citys == null || citys.length == 0) {
            mCurrentCityName = "";
        } else {
            mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
            areas = mSchoolDatasMap.get(mCurrentCityName);
        }

        if (areas == null || areas.length == 0) {
            areas = new String[]{""};
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(mContext, areas));
        mViewDistrict.setCurrentItem(0);
        if (areas != null && areas.length > 0) {
            mCurrentDistrictName = areas[0];
        } else {
            mCurrentDistrictName = "";
        }
    }

    class IsHaveListener extends ShowToastTaskEventListener {

        public IsHaveListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == ishaveJLPTaskId) {
                ishaveJLPTaskId = -1;

                if (data != null) {

                    JSONObject json = (JSONObject) data;
                    String isHave = json.getString("typeId");
                    PalLog.e("是否返回纪录片", isHave);
                    if (isHave != null) {
                        RadioGroup.LayoutParams params = new
                                RadioGroup.LayoutParams(screenWidth / 3,
                                RadioGroup.LayoutParams.WRAP_CONTENT);
//                        rgChannel.addView(jilupianBtn, params);

                    }

                }
            } else if (taskId == getSchoolTaskId) {
                List<CountryInfo> countryList = new ArrayList<CountryInfo>();
                if (data != null) {

                    countryList = (List<CountryInfo>) data;
                    allCounties = new String[countryList.size()];
                    if (countryList != null && countryList.size() > 0) {

                        for (int i = 0; i < countryList.size(); i++) {
                            allCounties[i] = countryList.get(i).getCountryName();
                            List<CityInfo> cityList = countryList.get(i).getList();
                            String[] allCities = new String[cityList.size()];
                            if (cityList != null && cityList.size() > 0) {
                                for (int j = 0; j < cityList.size(); j++) {
                                    allCities[j] = cityList.get(j).getCityName();
                                    List<SchoolInfo> schoolList = cityList.get(j).getSchoolList();
                                    String[] allSchool = new String[schoolList.size()];
                                    if (schoolList != null && schoolList.size() > 0) {
                                        for (int k = 0; k < schoolList.size(); k++) {
                                            allSchool[k] = schoolList.get(k).getSchoolName();
                                        }
                                        mSchoolDatasMap.put(allCities[j], allSchool);
                                        area.setClickable(true);
                                    }

                                }
                            }

                            mCitisDatasMap.put(countryList.get(i).getCountryName(), allCities);

                        }
                    }


                    if (countryList != null && !countryList.isEmpty()) {
                        mCurrentProviceName = countryList.get(0).getCountryName();
                        List<CityInfo> cityList = countryList.get(0).getList();
                        if (cityList != null && !cityList.isEmpty()) {
                            mCurrentCityName = cityList.get(0).getCityName();
                            List<SchoolInfo> districtList = cityList.get(0).getSchoolList();
                            if (districtList != null && !districtList.isEmpty()) {
                                mCurrentDistrictName = districtList.get(0).getSchoolName();
                            }

                        }
                    }
                    setUpData();
                }


            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = allCounties[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null || cities.length == 0) {
            cities = new String[]{""};
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(mContext, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }

    private void setUpData() {
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(mContext, allCounties));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        mViewDistrict.setVisibleItems(7);
        updateCities();
        updateAreas();
    }

    private void doIsHaveJLP() {
//        IsHaveJLPTask task = new IsHaveJLPTask();
//        task.addListener(new ShouYeFragment.IsHaveListener(mContext));
//        ishaveJLPTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void doGetAreaSchool() {
        AreaCitySchoolTask acsTask = new AreaCitySchoolTask();
        acsTask.addListener(new UserInfoActivity.IsHaveListener(mContext));
        getSchoolTaskId = getEatShowApp().getTaskManager().addTask(acsTask);
    }
}
